package online.shenjian.cloud.api.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.util.DateUtils;
import online.shenjian.cloud.api.model.Rank;
import online.shenjian.cloud.api.service.CoinService;
import online.shenjian.cloud.client.cloud.dto.RankDto;
import online.shenjian.cloud.common.CommonDtoUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CoinServiceImpl implements CoinService {

    private MongoTemplate mongoTemplate;

    public CoinServiceImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public List<RankDto> mktCapTop10() {
        Criteria criteria = new Criteria();
        Date date = DateUtils.parseDate(DateUtils.format(new Date(), "yyyy-MM-dd"));
        criteria.andOperator(Criteria.where("rank").lte(20), Criteria.where("c_date").gte(date));
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Order.asc("rank")));
        List<Rank> rankList = mongoTemplate.find(query, Rank.class);
        if (CollectionUtil.isEmpty(rankList)) {
            date = DateUtils.parseDate(DateUtils.format(org.apache.commons.lang3.time.DateUtils.addDays(new Date(), -1), "yyyy-MM-dd"));
            criteria = new Criteria();
            criteria.andOperator(Criteria.where("rank").lte(20), Criteria.where("c_date").gte(date));
            query = new Query(criteria);
            query.with(Sort.by(Sort.Order.asc("rank")));
            rankList = mongoTemplate.find(query, Rank.class);
        }
        return CommonDtoUtils.transformList(rankList, RankDto.class);
    }
}
